import { cloneDeep } from 'lodash';
import { useEffect, useState } from 'react';
import { getTreeData } from '@/utils/tool';
const useTableChangeAll = (params, getData, type, required = [] // params中满足必选参数才发起请求
) => {
    const [dataSource, setDataSource] = useState([]);
    const [total, setTotal] = useState(0);
    const [sorterField, setSorterField] = useState('');
    const [order, setOrder] = useState('');
    const [pageNum, setPageNum] = useState(params.pageNum || 1);
    const [pageSize, setPageSize] = useState(params.pageSize || 10);
    const [loading, setLoading] = useState(false);
    useEffect(() => {
        ;
        (async () => {
            const keys = Reflect.ownKeys(params);
            const flag = required.every((item) => keys.includes(item));
            flag && (await getDataList());
        })();
    }, [params, sorterField, order]);
    const getDataList = async () => {
        setLoading(true);
        let target = {};
        target.pageNum = 1;
        target.pageSize = 9999;
        const keys = Reflect.ownKeys(params);
        if (keys.length > 0) {
            target = { ...params, ...target };
        }
        let res = await getData(target);
        if (Array.isArray(res)) {
            setTotal(res.length);
            setDataSource(res);
            return;
        }
        res = res || {};
        const { list = [], total = 0, records = [] } = res;
        // const nData = cloneDeep(dataSource)
        if (type === 'tree' && records) {
            const treeData = getTreeData(list);
            setTotal(treeData.length);
            setDataSource(treeData);
        }
        if (type !== 'tree' && records) {
            setTotal(total);
            setDataSource(records);
            // if (pageNum === 1) {
            //   setDataSource(records)
            // } else {
            //   setDataSource([...nData, ...records])
            // }
        }
        setLoading(false);
    };
    const tableChange = (pagination, _filters, sorter) => {
        const { current = 1, pageSize = 20 } = pagination;
        setPageNum(current);
        setPageSize(pageSize);
        const { field, order } = sorter;
        setSorterField(field);
        setOrder(order);
    };
    const changeData = (field, value, idx) => {
        const newData = cloneDeep(dataSource);
        newData[idx][field] = value;
        setDataSource(newData);
    };
    return {
        tableChange,
        dataSource,
        total,
        sorterField,
        order,
        pageNum,
        pageSize,
        getDataList,
        changeData,
        loading
    };
};
export default useTableChangeAll;
